import { RequestStatus } from "./const";
import AppServer from "./appServer";
import CancelToken from "../../engine/cancel";
// @ts-ignore
import utils from "@/components/common/tui-utils/tui-utils.js";
import type { RequestDefaultConfig } from "../request.type";
import type { InnerRequestConfig } from "../../engine/types/engine.type";
class AppRequest {
    status: RequestStatus;
    uuid: string;
    _cancel: {
        token: CancelToken;
        cancel: (msg?: string) => void;
    };
    innerConfig: InnerRequestConfig;
    constructor(c: RequestDefaultConfig) {
        this.status = RequestStatus.waiting;
        this.uuid = utils.getUUID();
        // 初始化 cancel
        let cancelToken = CancelToken.source();
        this._cancel = cancelToken;
        // 配置项
        let innerConfig: InnerRequestConfig = {
            ...c,
            cancelToken: cancelToken.token,
        };
        this.innerConfig = innerConfig;
    }

    // 请求
    run() {
        let config = this.innerConfig || {};
        let that = this;
        return new Promise<{ res: any; config: InnerRequestConfig }>((resolve, reject) => {
            AppServer.appServer.request({
                ...config,
                readyToRequest() {
                    that.status = RequestStatus.loading;
                },
                success(result) {
                    that.status = RequestStatus.success;
                    resolve(result);
                },
                fail(e) {
                    that.status = RequestStatus.fail;
                    reject(e);
                },
            });
        });
    }

    // 取消请求
    cancel() {
        // 判断状态
        if (this.status === RequestStatus.success || this.status === RequestStatus.fail) {
            return;
        }
        this._cancel.cancel();
    }

    // 请求
    static request(c: RequestDefaultConfig) {
        let req = new AppRequest(c);
        return req;
    }
}

export { AppRequest };
